﻿using HZYProject.Core.Repositories;
using HZYProject.Domain;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace HZYProject.Web.Controllers
{
    public class AccountController : Controller
    {

        private readonly IRepository<User, int> _userRepository;

        public AccountController(IRepository<User, int> userRepository)
        {
            _userRepository = userRepository;
        }

        [HttpGet("login")]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost("login")]
        public IActionResult Login(string uName, string password)
        {
            var user = _userRepository.FirstOrDefault(x => x.UserName == uName);
            if (user != null)
            {
                if (user.PassWord == password)
                {

                    var Claims = new List<Claim>()
                            {
                                new Claim(ClaimTypes.Name,uName)
                            };
                    var Identity = new ClaimsIdentity(Claims, "Identity");

                    var userPrincipal = new ClaimsPrincipal(new[] { Identity });

                    HttpContext.SignInAsync(userPrincipal);

                    return Json(new { StatusCode = 1, Msg = "登录成功" });
                }
            }
            return Json(new { StatusCode = 0, Msg = "用户名或密码错误" });
        }
    }
}
